﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyOA.BLL;
using MyOA.Model;

namespace MyOA.UI.ScheduleManage.PersonSchedule
{
    public partial class SaveMySchedule : System.Web.UI.Page
    {

        SaveMyScheduleManage manage = new SaveMyScheduleManage();
        /// <summary>
        /// 给预约人那个LISTBOX绑定数据
        /// </summary>
        /// <param name="scheduleId">根据个人日程ID</param>
        protected void listBoxDataBind(int scheduleId)
        {
            if (lbPreContract.Items.Count > 0)
            {
                lbPreContract.Items.Clear();
            }
            IList<UserInfo> userInfos = manage.getUserInfosByScheduleId(scheduleId);

            foreach (UserInfo userInfo in userInfos)
            {
                string branchShortName = userInfo.Depart.Branch.BranchShortName;
                string departName = userInfo.Depart.DepartName;
                string loginId = userInfo.LoginId;
                ListItem item = new ListItem();
                item.Text = branchShortName + "-" + departName + "-" + loginId;
                item.Value = loginId;
                lbPreContract.Items.Add(item);
            }
        }

        /// <summary>
        /// 给那个显示全部用户的树形菜单绑定数据
        /// </summary>
        protected void TreeViewDataBind()
        {
            if (tvUserInfo.Nodes.Count > 0)
            {
                tvUserInfo.Nodes.Clear();
            }
            IList<BranchInfo> branches = manage.getAllBranchInfo();
            IList<DepartInfo> departs = manage.getAllDepartInfo();
            IList<UserInfo> users = manage.getAllUserInfo();

            foreach (BranchInfo branch in branches)
            {
                TreeNode tnBranch = new TreeNode(branch.BranchShortName, branch.BranchId.ToString(), "~/Images/menuclose.gif");



                foreach (DepartInfo depart in departs)
                {
                    if (tnBranch.Value == depart.Branch.BranchId.ToString())
                    {
                        TreeNode tnDepart = new TreeNode(depart.DepartName, depart.DepartId.ToString(), "~/Images/CloseTree.gif");
                        tnBranch.ChildNodes.Add(tnDepart);

                        foreach (UserInfo user in users)
                        {
                            if (tnDepart.Value == user.Depart.DepartId.ToString())
                            {
                                TreeNode tnUser = new TreeNode(user.LoginId, user.UserId.ToString(), "~/Images/person.gif");
                                tnDepart.ChildNodes.Add(tnUser);
                            }
                        }
                    }

                }
                tvUserInfo.Nodes.Add(tnBranch);
            }
            //开始默认折叠菜单
            tvUserInfo.CollapseAll();

        }
        /// <summary>
        /// 修改个人日程状态下 对个人日程信息进行数据绑定
        /// </summary>
        /// <param name="schedule">要绑定到控件上的数据源</param>
        protected void dataBind(Schedule schedule)
        {
            txtTitle.Text = schedule.Title;
            txtAddress.Text = schedule.Address;
            ddlMeetingClass.SelectedValue = schedule.Meeting.MeetingId.ToString();
            txtStart.Text = schedule.BeginTime.ToString();
            txtEnd.Text = schedule.EndTime.ToString();
            txtContent.Text = schedule.SchContent;
            lblCreateDate.Text = schedule.CreateTime.ToString();
            lblCreateUser.Text = schedule.CreateUser.LoginId;
            listBoxDataBind(schedule.ScheduleId);
        }

        /// <summary>
        /// 构建修改 新增个人日程要用的个人日程实体
        /// </summary>
        /// <returns>个人日程实体数据</returns>
        protected Schedule createSchedule()
        {
            Schedule schedule = new Schedule();
            //修改个人日程时 获取要修改的个人日程ID
            if (Request.QueryString["update"] != null)
            {
                //取得当前日程信息
                string today = Request.QueryString["today"];
                Schedule currentSchedule = (Schedule)Session["schedule" + today];
                schedule.ScheduleId = currentSchedule.ScheduleId;
            }

            schedule.Title = txtTitle.Text;
            schedule.Address = txtAddress.Text;
            schedule.BeginTime = DateTime.Parse(txtStart.Text);
            schedule.EndTime = DateTime.Parse(txtEnd.Text);

            //判断是修改还是新增 新增的创建时间则是选中的时间
            if (lblCreateDate.Text == string.Empty)
            {
                //创建时间是选中的那个日子+上当前时间的小时 分 秒
                DateTime currentTime = DateTime.Parse(Request.QueryString["today"] + " " + DateTime.Now.ToString("hh:mm:ss"));
                schedule.CreateTime = currentTime;
            }
            else
            {
                schedule.CreateTime = DateTime.Parse(lblCreateDate.Text);
            }


            schedule.SchContent = txtContent.Text;
            schedule.Meeting.MeetingId = int.Parse(ddlMeetingClass.SelectedValue);

            //根据登陆号来获取登陆用户信息
            UserInfo userInfo = manage.getUserInfoByLoginId((string)Session["loginId"]);
            schedule.CreateUser.UserId = userInfo.UserId;
            schedule.CreateDepart.DepartId = userInfo.Depart.DepartId;

            return schedule;
        }

        /// <summary>
        /// 构建新增 修改预约人的信息集合（注：日程ID未赋值 用时再赋值）
        /// </summary>
        /// <returns>预约人信息集合</returns>
        protected IList<PreContract> createPreContract()
        {
            IList<PreContract> preContracts = new List<PreContract>();

            foreach (ListItem item in lbPreContract.Items)
            {
                PreContract preContract = new PreContract();
                string loginId = item.Value;

                UserInfo userInfo = manage.getUserInfoByLoginId(loginId);

                preContract.User.UserId = userInfo.UserId;

                preContracts.Add(preContract);
            }


            return preContracts;
        }



        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                if (Session["loginId"] == null)
                {
                    Response.Redirect("~/Login.aspx");
                    return;

                }
                
                string loginId = (string)Session["loginId"];
                
                //string loginId = (string)Session["loginId"];



                string today = Request.QueryString["today"];
                //判断是否存在个人日程信息来 决定是否是新增个人日程还是修改个人日程
                if (Session["schedule" + today] != null && Request.QueryString["update"] != null)
                {
                    Schedule schedule = (Schedule)Session["schedule" + today];

                    //数据绑定
                    dataBind(schedule);

                }//这是从AllSchedule.aspx传来的
                else if (Request.QueryString["scheduleId"] != null)
                {
                    int scheduleId = int.Parse(Request.QueryString["scheduleId"]);
                    Schedule schedule = manage.getScheduleByScheduleId(scheduleId);
                    //数据绑定
                    dataBind(schedule);
                }
                else
                {
                    //是新增状态下 删除按钮不可用
                    btnDelete.Enabled = false;
                    //创建者
                    lblCreateUser.Text = loginId;
                    //Response.Write("保存");
                }
                //树形菜单数据绑定
                TreeViewDataBind();
              
            }
        }

        /// <summary>
        /// 删除预约人按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDeletePerson_Click(object sender, EventArgs e)
        {

            if (lbPreContract.SelectedItem == null)
            {
                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "", "<script>Alert('对不起，请选中要删除的人',null,null,'温馨提示')</script>", false);
            }
            else
            {
                IList<ListItem> list = new List<ListItem>();
                foreach (ListItem item in lbPreContract.Items)
                {
                    if (item.Selected)
                    {
                        list.Add(item);
                    }
                }
                foreach (ListItem item in list)
                {
                    lbPreContract.Items.Remove(item);
                }

            }
        }

        /// <summary>
        /// 删除个人日程按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            string today = Request.QueryString["today"];

            if (Session["schedule" + today] != null)
            {
                Schedule schedule = (Schedule)Session["schedule" + today];

                //获取这个个人日程的预约人信息集合
                IList<PreContract> preContracts = null;
                preContracts = manage.getPreContractByScheduleId(schedule.ScheduleId);

                //弹出是否删除成功的变量
                string message = string.Empty;
                //根据判断这个个人日程是否有预约人信息
                //来进行不同的存储过程
                if (preContracts.Count > 0)//要删除预约人表
                {
                    if (manage.DeleteScheduleAndPreContractByScheduleId(schedule.ScheduleId))
                    {
                        message = "删除成功";
                    }
                    else
                    {
                        message = "删除失败";
                    }
                }
                else//不用删除预约人表
                {
                    if (manage.DeleteScheduleByScheduleId(schedule.ScheduleId))
                    {
                        message = "删除成功";
                    }
                    else
                    {
                        message = "删除失败";
                    }
                }

                string script = string.Format("<script>Alert('{0}',null,null,'温馨提示',aHref)</script>", message);
                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "", script, false);
            }
        }

        /// <summary>
        /// 保存个人日程按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            //增加或修改是否成功后弹出的信息
            string message = string.Empty;
            Schedule schedule = createSchedule();


            //新增个人日程
            if (Request.QueryString["update"] == null)
            {

                //新增有预约人信息的个人日程
                if (lbPreContract.Items.Count > 0)
                {
                    //预约人ID组成的字符串
                    string usersId = string.Empty;
                    //预约人集合
                    IList<PreContract> preContracts = createPreContract();
                    foreach (PreContract item in preContracts)
                    {

                        usersId += item.User.UserId + ",";

                    }
                    usersId = usersId.Substring(0, usersId.LastIndexOf(","));
                    if (manage.insertScheduleAndPreContract(schedule, usersId) > 0)
                    {

                        message = "新增个人日程成功";
                    }
                    else
                    {
                        message = "增加个人日程失败";
                    }



                }
                //新增没有预约人信息的个人日程
                else
                {
                    if (manage.insertSchedule(schedule))
                    {

                        message = "新增个人日程成功";
                    }
                    else
                    {
                        message = "增加个人日程失败";
                    }
                }

            }
            //修改日程
            else
            {

                //数据库里的预约人信息和LISTBOX里的预约人信息是否一致的变量
                bool result = false;
                //删除预约人的集合
                IList<PreContract> deletePreContract = new List<PreContract>();
                //增加预约人的集合
                IList<PreContract> insertPreContract = new List<PreContract>();


                //获取这个个人日程的预约人信息集合
                IList<PreContract> preContracts = null;
                preContracts = manage.getPreContractByScheduleId(schedule.ScheduleId);

                //原来数据库中有预约人信息
                if (preContracts.Count > 0)
                {
                    if (lbPreContract.Items.Count > 0)
                    {
                        //LISTBOX里的预约人信息 注：scheduleID未赋值
                        IList<PreContract> listPreContract = createPreContract();
                        //给LISTBOX里的预约人信息的个人日程ID赋值
                        for (int i = 0; i < listPreContract.Count; i++)
                        {
                            listPreContract[i].Schedule.ScheduleId = schedule.ScheduleId;
                        }
                        //提取出来的数据库与LISTBOX相等的用户ID集合
                        IList<int> usersId = new List<int>();
                        //和数据库里的数据进行比较(用户名相等)，把相等的用户ID提取出来
                        foreach (PreContract pre in preContracts)
                        {
                            //和LISTBOX中的预约人每个都进行比较
                            for (int i = 0; i < listPreContract.Count; i++)
                            {
                                if (pre.User.UserId == listPreContract[i].User.UserId)
                                {
                                    usersId.Add(listPreContract[i].User.UserId);
                                    break;
                                }
                            }
                        }
                        //提取出来的相同用户ID集合个数与原先数据库中的用户个数一样 则只修改个人日程表
                        if (usersId.Count == preContracts.Count && usersId.Count == listPreContract.Count)
                        {
                            result = true;
                        }
                        //提取出来的比原先数据库的少(则要进行增 删预约人表)
                        else
                        {
                            result = false;
                            //没有一个是相同的 就要把原先数据库
                            //的数据全部删除 然后 再新增
                            if (usersId.Count == 0)
                            {
                                deletePreContract = preContracts;
                                insertPreContract = listPreContract;
                            }
                            //把相同的ID 保留下来不进行删操作
                            else
                            {
                                //如果相同的ID小于数据库里的ID数量 说明要进行删除操作
                                if (usersId.Count < preContracts.Count)
                                {
                                    //获取删除的集合
                                    deletePreContract = preContracts;

                                    for (int j = 0; j < preContracts.Count; j++)
                                    {

                                        for (int i = 0; i < usersId.Count; i++)
                                        {
                                            if (preContracts[j].User.UserId == usersId[i])
                                            {

                                                //移除具有相同用户ID的项 不进行删除
                                                deletePreContract.RemoveAt(j);
                                                break;
                                            }
                                        }
                                    }
                                }


                                //如果相同的ID数量小于LISTBOX里的ID数量 说明要增加
                                if (usersId.Count < listPreContract.Count)
                                {


                                    //获取新增的集合
                                    insertPreContract = listPreContract;
                                    for (int j = 0; j < listPreContract.Count; j++)
                                    {
                                        for (int i = 0; i < usersId.Count; i++)
                                        {
                                            if (listPreContract[j].User.UserId == usersId[i])
                                            {

                                                //移除具有相同用户ID的项 不进行删除
                                                insertPreContract.RemoveAt(j);
                                                break;
                                            }
                                        }
                                    }
                                }

                            }

                        }

                    }
                    //删除原先数据库里所有的预约人信息
                    else
                    {
                        //给删除预约人集合赋值
                        deletePreContract = preContracts;
                        result = false;
                    }
                }
                //原来数据库中没有预约人信息
                else
                {
                    //新增预约人信息
                    if (lbPreContract.Items.Count > 0)
                    {
                        result = false;
                        //LISTBOX里的预约人信息 注：scheduleID未赋值
                        IList<PreContract> listPreContract = createPreContract();
                        //给LISTBOX里的预约人信息的个人日程ID赋值
                        for (int i = 0; i < listPreContract.Count; i++)
                        {
                            listPreContract[i].Schedule.ScheduleId = schedule.ScheduleId;
                        }
                        insertPreContract = listPreContract;
                    }
                    //没有新增预约人信息
                    else
                    {
                        result = true;
                    }
                }



                //不必修改预约人信息的个人日程
                if (result)
                {
                    if (manage.updateScheduleByScheduleId(schedule))
                    {
                        message = "修改个人日程成功";
                    }
                    else
                    {
                        message = "修改个人日程失败";
                    }
                    //message = "不修改预约人";
                }
                else//修改有预约人的个人日程
                {
                    //message = "修改预约人";
                    //if (insertPreContract.Count>0)
                    //{
                    //    message += "增加预约人";
                    //} if (deletePreContract.Count>0)
                    //{
                    //    message += "删除预约人";
                    //}

                    //增加和删除预约人信息的USERID字符串变量
                    string insertUsersId = string.Empty;
                    string deleteUsersId = string.Empty;

                    //修改个人日程并只增加预约人信息
                    if (insertPreContract.Count > 0 && deletePreContract.Count == 0)
                    {
                        foreach (PreContract item in insertPreContract)
                        {
                            insertUsersId += item.User.UserId + ",";
                        }
                        insertUsersId = insertUsersId.Substring(0, insertUsersId.LastIndexOf(","));

                        if (manage.updateScheduleAndInsertPreContract(schedule, insertUsersId) > 0)
                        {
                            message = "修改个人日程成功";
                        }
                        else
                        {
                            message = "修改个人日程失败";
                        }
                    }

                    //修改个人日程只删除预约人信息
                    else if (insertPreContract.Count == 0 && deletePreContract.Count > 0)
                    {
                        foreach (PreContract item in deletePreContract)
                        {
                            deleteUsersId += item.User.UserId + ",";
                        }
                        deleteUsersId = deleteUsersId.Substring(0, deleteUsersId.LastIndexOf(","));

                        if (manage.updateScheduleAndDeletePreContract(schedule, deleteUsersId) > 0)
                        {
                            message = "修改个人日程成功";
                        }
                        else
                        {
                            message = "修改个人日程失败";
                        }
                    }
                    //修改个人日程并即增加预约人又删除预约人
                    else if (insertPreContract.Count > 0 && deletePreContract.Count > 0)
                    {
                        foreach (PreContract item in insertPreContract)
                        {
                            insertUsersId += item.User.UserId + ",";
                        }
                        insertUsersId = insertUsersId.Substring(0, insertUsersId.LastIndexOf(","));

                        foreach (PreContract item in deletePreContract)
                        {
                            deleteUsersId += item.User.UserId + ",";
                        }
                        deleteUsersId = deleteUsersId.Substring(0, deleteUsersId.LastIndexOf(","));


                        if (manage.updateScheduleAndInsertAndDeletePreContract(schedule, insertUsersId, deleteUsersId) > 0)
                        {
                            message = "修改个人日程成功";
                        }
                        else
                        {
                            message = "修改个人日程失败";
                        }
                    }


                }


            }
            string script = string.Format("<script>Alert('{0}',null,null,'温馨提示',aHref)</script>", message);
            ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "", script, false);
        }

        /// <summary>
        /// 树形菜单选中不同选项发生的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void tvUserInfo_SelectedNodeChanged(object sender, EventArgs e)
        {
            ModalPopupExtender1.Hide();
            //判断是否选中的是用户节点
            if (tvUserInfo.SelectedNode.ChildNodes.Count != 0)
            {
                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "", "<script>Error('请选择用户',null,null,'温馨提示')</script>", false);
                return;
            }
            string user = tvUserInfo.SelectedNode.Text;
            if (user == Session["loginId"].ToString())
            {
                ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "", "<script>Error('不能添加自己',null,null,'温馨提示')</script>", false);
                return;
            }
            string depart = tvUserInfo.SelectedNode.Parent.Text;
            string branch = tvUserInfo.SelectedNode.Parent.Parent.Text;


            string name = branch + "-" + depart + "-" + user;

            foreach (ListItem item in lbPreContract.Items)
            {
                if (item.Text == name)
                {
                    ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "", "<script>Error('此用户已经存在列表中',null,null,'温馨提示')</script>", false);
                    return;
                }
            }
            ListItem lt = new ListItem(name, user);
            lbPreContract.Items.Add(lt);

        }


    }
}
